import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import compression from 'compression';
import { config } from './config';
import { DatabaseInitializer } from './database/init';
import { dorisConnectionManager } from './database/connectors/DorisConnectionManager';

// 导入路由
import connectionsRouter from './routes/connections';
import executionsRouter from './routes/executions';
import scriptsRouter from './routes/scripts';
import versionsRouter from './routes/versions';
import foldersRouter from './routes/folders';
import schemaRouter from './routes/schemaRoutes';

// 创建Express应用
const app = express();

// 中间件配置
app.use(helmet()); // 安全头
app.use(cors(config.cors)); // CORS配置
app.use(compression()); // 响应压缩
app.use(morgan('combined')); // 请求日志
app.use(express.json({ limit: '10mb' })); // JSON解析
app.use(express.urlencoded({ extended: true, limit: '10mb' })); // URL编码解析

// 健康检查端点
app.get('/health', async (_req, res) => {
  try {
    const healthCheck = await DatabaseInitializer.healthCheck();
    
    res.status(healthCheck.overall ? 200 : 503).json({
      status: healthCheck.overall ? 'healthy' : 'unhealthy',
      timestamp: new Date().toISOString(),
      services: {
        postgresql: healthCheck.postgresql ? 'up' : 'down',
        redis: healthCheck.redis ? 'up' : 'down'
      },
      version: process.env.npm_package_version || '1.0.0',
      environment: config.nodeEnv
    });
  } catch (error) {
    res.status(503).json({
      status: 'error',
      message: 'Health check failed',
      error: error instanceof Error ? error.message : 'Unknown error'
    });
  }
});

// API路由
app.use('/api/connections', connectionsRouter);
app.use('/api/executions', executionsRouter);
app.use('/api/scripts', scriptsRouter);
app.use('/api/versions', versionsRouter);
app.use('/api/folders', foldersRouter);
app.use('/api/schema', schemaRouter);

// 基础路由
app.get('/', (_req, res) => {
  res.json({
    message: 'DW SQL脚本管理工具 API',
    version: '1.0.0',
    environment: config.nodeEnv,
    timestamp: new Date().toISOString()
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    error: 'Not Found',
    message: `Route ${req.originalUrl} not found`,
    timestamp: new Date().toISOString()
  });
});

// 全局错误处理
app.use((err: any, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
  console.error('Global error handler:', err);
  
  res.status(err.status || 500).json({
    error: config.nodeEnv === 'production' ? 'Internal Server Error' : err.message,
    timestamp: new Date().toISOString(),
    ...(config.nodeEnv !== 'production' && { stack: err.stack })
  });
});

// 启动服务器
async function startServer() {
  try {
    console.log('🚀 Starting DW SQL Script Manager Backend...');
    
    // 初始化数据库连接
    console.log('📊 Initializing database connections...');
    const dbInitialized = await DatabaseInitializer.testConnections();
    
    if (!dbInitialized) {
      console.error('❌ Database initialization failed');
      process.exit(1);
    }
    
    console.log('✅ Database connections established');
    
    // 启动HTTP服务器
    const server = app.listen(config.port, () => {
      console.log(`🌟 Server running on port ${config.port}`);
      console.log(`📝 Environment: ${config.nodeEnv}`);
      console.log(`🔗 Health check: http://localhost:${config.port}/health`);
      console.log(`🏠 API base: http://localhost:${config.port}/`);
    });
    
    // 优雅关闭处理
    const gracefulShutdown = async (signal: string) => {
      console.log(`\n🛑 Received ${signal}, starting graceful shutdown...`);
      
      server.close(async () => {
        console.log('🔌 HTTP server closed');
        
        try {
          // 关闭Doris连接管理器
          await dorisConnectionManager.closeAllConnections();
          console.log('🔌 Doris connections closed');
          
          await DatabaseInitializer.shutdown();
          console.log('💾 Database connections closed');
          console.log('✅ Graceful shutdown completed');
          process.exit(0);
        } catch (error) {
          console.error('❌ Error during shutdown:', error);
          process.exit(1);
        }
      });
      
      // 强制退出超时
      setTimeout(() => {
        console.error('⏰ Shutdown timeout, forcing exit');
        process.exit(1);
      }, 10000);
    };
    
    // 监听关闭信号
    process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
    process.on('SIGINT', () => gracefulShutdown('SIGINT'));
    
    // 监听未捕获的异常
    process.on('uncaughtException', (error) => {
      console.error('💥 Uncaught Exception:', error);
      gracefulShutdown('uncaughtException');
    });
    
    process.on('unhandledRejection', (reason, promise) => {
      console.error('💥 Unhandled Rejection at:', promise, 'reason:', reason);
      gracefulShutdown('unhandledRejection');
    });
    
  } catch (error) {
    console.error('💥 Failed to start server:', error);
    process.exit(1);
  }
}

// 启动服务器
if (require.main === module) {
  startServer();
}

export default app;